package ddalarm

import (
	"crypto/hmac"
	"crypto/sha256"
	"encoding/base64"
	"encoding/json"
	"fmt"
	"time"

	"testkjcld.bhecard.com/gitlab/kit/esim/config"
)

type Config struct {
	MsgType     string     `json:"msgtype"` // 消息类型，此时固定为：text
	At          *AtContent `json:"at"`
	AccessToken string
	AccessKey   string
	URL         string
	ProxyURL    string
}

func (c *Config) setDefaultConfig(conf config.Config) {
	if c.URL == "" {
		c.URL = conf.GetString("alarm_url")
	}

	c.ProxyURL = conf.GetString("alarm_proxy")

	if c.AccessToken == "" {
		c.AccessToken = conf.GetString("alarm_access_token")
	}

	if c.AccessKey == "" {
		c.AccessKey = conf.GetString("alarm_access_key")
	}

	if c.MsgType == "" {
		c.MsgType = conf.GetString("alarm_msg_type")
	}

	if c.At == nil {
		c.At = new(AtContent)
	}

	c.At.IsAtAll = conf.GetBool("alarm_is_atall")

	c.At.AtMobiles = conf.GetStringSlice("alarm_at_mobiles")
}

func (c *Config) builderURL() string {
	timeStamp := fmt.Sprintf("%d", time.Now().UnixMilli())
	signBlock := timeStamp + "\n" + c.AccessKey
	mac := hmac.New(sha256.New, []byte(c.AccessKey))
	mac.Write([]byte(signBlock))
	signature := base64.StdEncoding.EncodeToString(mac.Sum(nil))

	return fmt.Sprintf("%s?access_token=%s&timestamp=%s&sign=%s", c.URL, c.AccessToken, timeStamp, signature)
}

func (c *Config) Marshal() []byte {
	buf, _ := json.Marshal(c)
	return buf
}
